package accounts

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"minititok/Entities"
	"minititok/Services"
	"net/http"
	"strconv"
)

func getProfile(c *gin.Context) {
	uid := c.Query("uid")
	user, _ := c.Get("user")
	currUser, ok := user.(*Entities.User)
	if !ok {
		_ = c.Error(fmt.Errorf("token验证不通过"))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "Token验证不通过"})
		return
	}
	intUid, _ := strconv.Atoi(uid)
	uidUser, _ := Services.FindUserByUID(intUid)
	count, err := Services.GetCountByAuthor(uidUser.Username)
	if err != nil {
		_ = c.Error(fmt.Errorf("当前登入用户不存在"))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "用户不存在"})
		return
	}
	currUid := strconv.Itoa(currUser.UID)
	data := gin.H{
		"uid":           uidUser.UID,
		"followers":     10,
		"following":     20,
		"username":      uidUser.Nickname,
		"avatar":        uidUser.Avatar,
		"videoCount":    count,
		"isCurrentUser": uid == currUid,
	}
	c.JSON(http.StatusOK, gin.H{"data": data})
}

func cheackUid(c *gin.Context) {
	user, _ := c.Get("user")
	currUser, _ := user.(*Entities.User)
	c.JSON(200, gin.H{"data": gin.H{"uid": currUser.UID}})
}

func getProfileVideo(c *gin.Context) {
	page := c.Query("page")
	pageSize := c.Query("pageSize")
	uid := c.Query("uid")
	var videos []Entities.Video
	var err error
	user, _ := c.Get("user")
	_, uerr := user.(*Entities.User)
	if !uerr {
		_ = c.Error(fmt.Errorf("token验证错误"))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "token错误"})
		return
	}
	intUid, _ := strconv.Atoi(uid)
	uidUser, _ := Services.FindUserByUID(intUid)
	intPage, _ := strconv.Atoi(page)
	intPageSize, _ := strconv.Atoi(pageSize)
	videos, err = Services.GetOneselfVideoByPage(uidUser.Username, intPage, intPageSize)
	if err != nil {
		_ = c.Error(fmt.Errorf("资源不存在:" + err.Error()))
		c.JSON(http.StatusUnauthorized, gin.H{"customMessage": "资源错误"})
	}
	data := gin.H{
		"items": []gin.H{},
	}
	var items []gin.H
	for _, v := range videos {
		items = append(items, gin.H{
			"av":       v.Av,
			"title":    v.Title,
			"duration": v.Duration,
			"stats": gin.H{
				"views": v.Views,
				"likes": v.Likes,
			},
			"cover_url": v.CoverURL,
			"uid":       uidUser.UID,
		})
	}
	data["items"] = items
	c.JSON(http.StatusOK, gin.H{"data": data})
}
